from django.shortcuts import render

# Create your views here.
from django.shortcuts import render, redirect, get_object_or_404
from django.contrib.auth.decorators import login_required, user_passes_test
from django.contrib import messages
from django.http import JsonResponse
from django.db.models import Count, Q, Sum, Avg
from django.utils import timezone
from django.db import transaction
from datetime import timedelta, datetime
import json

from django.views.decorators.http import require_http_methods

from users.models import User
from activities.models import Activity, ActivityCategory, ActivityRegistration
from points.models import UserPoints, PointsRecord, RewardExchange, Reward
from social.models import Follow, Message, SystemNotification
from .models import AdminLog


def is_admin_user(user):
    """检查用户是否是管理员"""
    return user.is_authenticated and (user.is_staff or user.is_superuser or user.user_type in ['admin', 'super_admin'])

def is_content_moderator(user):
    """检查用户是否是内容管理员"""
    return user.is_authenticated and (
        user.is_staff or
        user.user_type in ['admin', 'super_admin', 'moderator']
    )


def log_admin_action(request, action, description):
    """记录管理员操作日志"""
    # 确保 action 参数是有效的
    valid_actions = ['user_manage', 'activity_manage', 'system_manage']
    if action not in valid_actions:
        action = 'system_manage'  # 默认为系统管理

    AdminLog.objects.create(
        admin=request.user,
        action=action,
        description=description,
        ip_address=get_client_ip(request)
    )


def get_client_ip(request):
    """获取客户端IP"""
    x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
    if x_forwarded_for:
        ip = x_forwarded_for.split(',')[0]
    else:
        ip = request.META.get('REMOTE_ADDR')
    return ip


@login_required
@user_passes_test(is_admin_user)
def admin_dashboard(request):
    """后台管理仪表盘"""
    # 基础统计
    total_users = User.objects.count()
    total_activities = Activity.objects.count()
    total_categories = ActivityCategory.objects.count()

    # 今日统计
    today = timezone.now().date()
    today_users = User.objects.filter(date_joined__date=today).count()
    today_activities = Activity.objects.filter(created_at__date=today).count()

    # 待审核活动
    pending_activities = Activity.objects.filter(status='pending').count()

    # 活动状态分布
    activity_status_stats = Activity.objects.values('status').annotate(count=Count('id'))

    # 用户增长数据（最近30天）
    thirty_days_ago = timezone.now() - timedelta(days=30)
    user_growth_data = []
    activity_growth_data = []

    for i in range(30):
        date = thirty_days_ago + timedelta(days=i)
        user_count = User.objects.filter(date_joined__date=date).count()
        activity_count = Activity.objects.filter(created_at__date=date).count()

        user_growth_data.append({
            'date': date.strftime('%m-%d'),
            'count': user_count
        })
        activity_growth_data.append({
            'date': date.strftime('%m-%d'),
            'count': activity_count
        })

    # 热门活动分类
    popular_categories = ActivityCategory.objects.annotate(
        activity_count=Count('activity')
    ).order_by('-activity_count')[:5]

    # 最新待审核活动
    recent_pending_activities = Activity.objects.filter(status='pending').select_related('creator', 'category')[:5]

    # 最新注册用户
    recent_users = User.objects.all().order_by('-date_joined')[:5]

    # 管理员操作日志
    recent_logs = AdminLog.objects.select_related('admin').order_by('-created_at')[:10]

    context = {
        'total_users': total_users,
        'total_activities': total_activities,
        'total_categories': total_categories,
        'today_users': today_users,
        'today_activities': today_activities,
        'pending_activities': pending_activities,
        'activity_status_stats': activity_status_stats,
        'user_growth_data': json.dumps(user_growth_data),
        'activity_growth_data': json.dumps(activity_growth_data),
        'popular_categories': popular_categories,
        'recent_pending_activities': recent_pending_activities,
        'recent_users': recent_users,
        'recent_logs': recent_logs,
    }
    return render(request, 'dashboard/admin_dashboard.html', context)


@login_required
@user_passes_test(is_admin_user)
def user_management(request):
    """用户管理"""
    users = User.objects.all().order_by('-date_joined')

    # 搜索功能
    search_query = request.GET.get('search', '')
    if search_query:
        users = users.filter(
            Q(username__icontains=search_query) |
            Q(email__icontains=search_query) |
            Q(nickname__icontains=search_query)
        )

    # 状态筛选
    status_filter = request.GET.get('status', '')
    if status_filter:
        if status_filter == 'active':
            users = users.filter(is_active=True)
        elif status_filter == 'inactive':
            users = users.filter(is_active=False)
        elif status_filter == 'staff':
            users = users.filter(Q(is_staff=True) | Q(user_type__in=['admin', 'super_admin']))

    context = {
        'users': users,
        'search_query': search_query,
        'status_filter': status_filter,
    }
    return render(request, 'dashboard/user_management.html', context)


@login_required
@user_passes_test(is_admin_user)
def activity_management(request):
    """活动管理"""
    activities = Activity.objects.all().select_related('creator', 'category').order_by('-created_at')

    # 搜索功能
    search_query = request.GET.get('search', '')
    if search_query:
        activities = activities.filter(
            Q(title__icontains=search_query) |
            Q(description__icontains=search_query) |
            Q(creator__username__icontains=search_query)
        )

    # 状态筛选
    status_filter = request.GET.get('status', '')
    if status_filter:
        activities = activities.filter(status=status_filter)

    # 分类筛选
    category_filter = request.GET.get('category', '')
    if category_filter:
        activities = activities.filter(category_id=category_filter)

    categories = ActivityCategory.objects.all()

    # 统计信息
    pending_activities_count = Activity.objects.filter(status='pending').count()
    approved_activities_count = Activity.objects.filter(status='approved').count()
    total_participants = ActivityRegistration.objects.filter(status='registered').count()

    context = {
        'activities': activities,
        'categories': categories,
        'search_query': search_query,
        'status_filter': status_filter,
        'category_filter': category_filter,
        'pending_activities_count': pending_activities_count,
        'approved_activities_count': approved_activities_count,
        'total_participants': total_participants,
    }
    return render(request, 'dashboard/activity_management.html', context)


@login_required
@user_passes_test(is_admin_user)
def activity_delete(request, activity_id):
    """删除活动（后台管理）"""
    if request.method == 'POST':
        activity = get_object_or_404(Activity, id=activity_id)
        activity_title = activity.title

        # 记录删除前的信息用于日志
        creator_username = activity.creator.username
        participants_count = activity.current_participants

        # 删除活动
        activity.delete()

        log_admin_action(request, 'activity_manage',
                         f'删除活动: {activity_title} (创建者: {creator_username}, 参与人数: {participants_count})')
        messages.success(request, f'活动 "{activity_title}" 已删除')
        return JsonResponse({'success': True, 'message': '活动已删除'})

    return JsonResponse({'success': False, 'message': '请求方法错误'})

@login_required
@user_passes_test(is_admin_user)
def user_detail(request, user_id):
    """用户详情"""
    user = get_object_or_404(User, id=user_id)

    # 用户活动统计
    created_activities = Activity.objects.filter(creator=user)
    registered_activities = ActivityRegistration.objects.filter(user=user, status='registered')

    # 积分信息
    user_points = UserPoints.objects.filter(user=user).first()
    points_records = PointsRecord.objects.filter(user=user).order_by('-created_at')[:10]

    # 社交信息
    followers_count = Follow.objects.filter(following=user).count()
    following_count = Follow.objects.filter(follower=user).count()

    # 最近操作
    recent_activities = created_activities.order_by('-created_at')[:5]

    context = {
        'target_user': user,
        'created_activities': created_activities,
        'registered_activities': registered_activities,
        'user_points': user_points,
        'points_records': points_records,
        'followers_count': followers_count,
        'following_count': following_count,
        'recent_activities': recent_activities,
    }
    return render(request, 'dashboard/user_detail.html', context)


@login_required
@user_passes_test(is_admin_user)
def toggle_user_status(request, user_id):
    """切换用户状态"""
    if request.method == 'POST':
        user = get_object_or_404(User, id=user_id)
        user.is_active = not user.is_active
        user.save()

        action = "启用" if user.is_active else "禁用"
        log_admin_action(request, 'user_manage', f'{action}用户: {user.username}')
        messages.success(request, f'已{action}用户 {user.username}')

        return JsonResponse({'success': True, 'is_active': user.is_active})

    return JsonResponse({'success': False, 'message': '请求方法错误'})


@login_required
@user_passes_test(is_admin_user)
def set_user_type(request, user_id):
    """设置用户类型"""
    if request.method == 'POST':
        user = get_object_or_404(User, id=user_id)
        user_type = request.POST.get('user_type')

        if user_type in ['normal', 'admin', 'super_admin']:
            user.user_type = user_type
            user.save()

            log_admin_action(request, 'user_manage', f'设置用户类型: {user.username} -> {user_type}')
            messages.success(request, f'已设置用户 {user.username} 为 {user.get_user_type_display()}')
            return JsonResponse({'success': True, 'user_type': user_type})

    return JsonResponse({'success': False, 'message': '请求方法错误'})



def is_admin_user(user):
    """检查用户是否是管理员 - 放宽权限"""
    return user.is_authenticated and (
        user.is_staff or
        user.is_superuser or
        user.user_type in ['admin', 'super_admin', 'moderator']  # 添加 moderator
    )



@login_required
@user_passes_test(is_content_moderator)  # 使用更宽松的权限检查
@require_http_methods(["POST"])
def reject_activity(request, activity_id):
    """拒绝活动 - 添加拒绝原因"""
    try:
        print(f"用户 {request.user.username} 尝试拒绝活动 {activity_id}")
        print(
            f"用户权限: staff={request.user.is_staff}, superuser={request.user.is_superuser}, user_type={request.user.user_type}")

        # 解析请求数据
        if request.content_type == 'application/json':
            data = json.loads(request.body)
            reject_reason = data.get('reject_reason', '').strip()
        else:
            reject_reason = request.POST.get('reject_reason', '').strip()

        if not reject_reason:
            return JsonResponse({'success': False, 'message': '请填写拒绝原因'})

        # 获取活动
        activity = Activity.objects.get(id=activity_id)

        # 检查用户是否有权限操作此活动
        # 可以添加额外的权限检查，比如用户只能操作自己创建的活动等

        # 更新活动状态
        activity.status = 'rejected'
        activity.reject_reason = reject_reason
        activity.save()

        # 创建系统通知
        SystemNotification.objects.create(
            user=activity.creator,
            title='活动审核未通过',
            content=f'您创建的活动 "{activity.title}" 未通过审核。\n\n拒绝原因：{reject_reason}\n\n操作管理员：{request.user.username}',
            notification_type='activity_rejected',
            related_activity=activity,
            admin_user=request.user
        )

        print(f"活动 {activity_id} 拒绝成功")
        return JsonResponse({'success': True, 'message': '活动已拒绝'})

    except Activity.DoesNotExist:
        return JsonResponse({'success': False, 'message': '活动不存在'})
    except Exception as e:
        print(f"拒绝活动时出错: {str(e)}")
        import traceback
        print(traceback.format_exc())
        return JsonResponse({'success': False, 'message': f'服务器错误: {str(e)}'})


@login_required
@user_passes_test(is_content_moderator)  # 使用更宽松的权限检查，允许普通管理员操作
@require_http_methods(["POST"])
def approve_activity(request, activity_id):
    """批准活动"""

    try:
        activity = Activity.objects.get(id=activity_id)
        activity.status = 'approved'
        activity.save()

        # 创建系统通知
        SystemNotification.objects.create(
            user=activity.creator,
            title='活动审核通过',
            content=f'您创建的活动 "{activity.title}" 已通过审核，现在可以在活动列表中看到了。\n\n操作管理员：{request.user.username}',
            notification_type='activity_approved',
            related_activity=activity,
            admin_user=request.user
        )

        return JsonResponse({'success': True, 'message': '活动已通过'})

    except Activity.DoesNotExist:
        return JsonResponse({'success': False, 'message': '活动不存在'})
    except Exception as e:
        return JsonResponse({'success': False, 'message': str(e)})


@login_required
@user_passes_test(is_admin_user)
def system_analytics(request):
    """系统数据分析 - 增强可视化版本"""
    # 用户统计
    total_users = User.objects.count()
    active_users = User.objects.filter(is_active=True).count()
    new_users_today = User.objects.filter(date_joined__date=timezone.now().date()).count()
    new_users_week = User.objects.filter(date_joined__gte=timezone.now() - timedelta(days=7)).count()

    # 活动统计
    total_activities = Activity.objects.count()
    approved_activities = Activity.objects.filter(status='approved').count()
    pending_activities = Activity.objects.filter(status='pending').count()
    completed_activities = Activity.objects.filter(status='completed').count()

    # 参与统计
    total_registrations = ActivityRegistration.objects.count()
    total_checkins = ActivityRegistration.objects.filter(is_checked_in=True).count()
    checkin_rate = round((total_checkins / total_registrations * 100) if total_registrations > 0 else 0, 1)

    # 积分统计
    total_points = UserPoints.objects.aggregate(total=Sum('total_points'))['total'] or 0
    total_exchanges = RewardExchange.objects.count()
    active_points_users = UserPoints.objects.filter(available_points__gt=0).count()

    # 社交统计
    total_follows = Follow.objects.count()
    total_messages = Message.objects.count()

    # 活动分类分布
    category_stats = list(ActivityCategory.objects.annotate(
        activity_count=Count('activity')
    ).values('name', 'activity_count'))

    # 活动状态分布
    status_stats = list(Activity.objects.values('status').annotate(count=Count('id')))

    # 用户类型分布
    user_type_stats = list(User.objects.values('user_type').annotate(count=Count('id')))

    # 月度活动创建趋势（最近12个月）
    monthly_activity_data = []
    monthly_user_data = []
    monthly_registration_data = []

    for i in range(11, -1, -1):
        month_start = timezone.now().replace(day=1) - timedelta(days=30 * i)
        month_end = (month_start + timedelta(days=32)).replace(day=1) - timedelta(days=1)

        activity_count = Activity.objects.filter(
            created_at__range=[month_start, month_end]
        ).count()

        user_count = User.objects.filter(
            date_joined__range=[month_start, month_end]
        ).count()

        registration_count = ActivityRegistration.objects.filter(
            created_at__range=[month_start, month_end]
        ).count()

        monthly_activity_data.append({
            'month': month_start.strftime('%Y-%m'),
            'count': activity_count
        })

        monthly_user_data.append({
            'month': month_start.strftime('%Y-%m'),
            'count': user_count
        })

        monthly_registration_data.append({
            'month': month_start.strftime('%Y-%m'),
            'count': registration_count
        })

    # 热门活动（按参与人数）
    popular_activities = Activity.objects.filter(status='approved').annotate(
        registration_count=Count('registrations')
    ).order_by('-registration_count')[:10].values('title', 'registration_count')

    # 积分获取类型分布
    points_type_stats = list(PointsRecord.objects.values('type').annotate(
        total_points=Sum('points'),
        count=Count('id')
    ))

    # 用户活跃度（最近30天有活动的用户）
    thirty_days_ago = timezone.now() - timedelta(days=30)
    active_users_recent = User.objects.filter(
        Q(created_activities__created_at__gte=thirty_days_ago) |
        Q(registrations__created_at__gte=thirty_days_ago) |
        Q(activity_comments__created_at__gte=thirty_days_ago)
    ).distinct().count()

    context = {
        # 基础统计
        'total_users': total_users,
        'active_users': active_users,
        'new_users_today': new_users_today,
        'new_users_week': new_users_week,
        'total_activities': total_activities,
        'approved_activities': approved_activities,
        'pending_activities': pending_activities,
        'completed_activities': completed_activities,
        'total_registrations': total_registrations,
        'total_checkins': total_checkins,
        'checkin_rate': checkin_rate,
        'total_points': total_points,
        'total_exchanges': total_exchanges,
        'active_points_users': active_points_users,
        'total_follows': total_follows,
        'total_messages': total_messages,
        'active_users_recent': active_users_recent,

        # 图表数据
        'category_stats': json.dumps(category_stats),
        'status_stats': json.dumps(status_stats),
        'user_type_stats': json.dumps(user_type_stats),
        'monthly_activity_data': json.dumps(monthly_activity_data),
        'monthly_user_data': json.dumps(monthly_user_data),
        'monthly_registration_data': json.dumps(monthly_registration_data),
        'popular_activities': json.dumps(list(popular_activities)),
        'points_type_stats': json.dumps(points_type_stats),
    }
    return render(request, 'dashboard/system_analytics.html', context)


@login_required
@user_passes_test(is_admin_user)
def get_dashboard_stats(request):
    """获取仪表盘统计数据（AJAX）"""
    # 今日数据
    today = timezone.now().date()

    stats = {
        'today_users': User.objects.filter(date_joined__date=today).count(),
        'today_activities': Activity.objects.filter(created_at__date=today).count(),
        'pending_activities': Activity.objects.filter(status='pending').count(),
        'total_registrations_today': ActivityRegistration.objects.filter(created_at__date=today).count(),
    }

    return JsonResponse(stats)


@login_required
@user_passes_test(is_admin_user)
def admin_logs(request):
    """管理员操作日志"""
    logs = AdminLog.objects.select_related('admin').order_by('-created_at')

    # 搜索功能
    search_query = request.GET.get('search', '')
    if search_query:
        logs = logs.filter(
            Q(admin__username__icontains=search_query) |
            Q(description__icontains=search_query)
        )

    # 操作类型筛选
    action_filter = request.GET.get('action', '')
    if action_filter:
        logs = logs.filter(action=action_filter)

    # 统计信息
    total_logs = AdminLog.objects.count()
    user_manage_count = AdminLog.objects.filter(action='user_manage').count()
    activity_manage_count = AdminLog.objects.filter(action='activity_manage').count()

    # 今日日志
    today = timezone.now().date()
    today_logs = AdminLog.objects.filter(created_at__date=today).count()

    context = {
        'logs': logs,
        'search_query': search_query,
        'action_filter': action_filter,
        'total_logs': total_logs,
        'user_manage_count': user_manage_count,
        'activity_manage_count': activity_manage_count,
        'today_logs': today_logs,
    }
    return render(request, 'dashboard/admin_logs.html', context)


#活动分类相关
@login_required
@user_passes_test(is_admin_user)
def category_management(request):
    """活动分类管理"""
    categories = ActivityCategory.objects.all().order_by('-created_at')

    # 搜索功能
    search_query = request.GET.get('search', '')
    if search_query:
        categories = categories.filter(name__icontains=search_query)

    context = {
        'categories': categories,
        'search_query': search_query,
    }
    return render(request, 'dashboard/category_management.html', context)


@login_required
@user_passes_test(is_admin_user)
def category_create(request):
    """创建活动分类"""
    if request.method == 'POST':
        name = request.POST.get('name')
        description = request.POST.get('description', '')
        icon = request.POST.get('icon', '')
        is_default = request.POST.get('is_default') == 'on'

        if not name:
            return JsonResponse({'success': False, 'message': '分类名称不能为空'})

        # 检查分类名称是否已存在
        if ActivityCategory.objects.filter(name=name).exists():
            return JsonResponse({'success': False, 'message': '分类名称已存在'})

        # 创建分类
        category = ActivityCategory.objects.create(
            name=name,
            description=description,
            icon=icon,
            is_default=is_default
        )

        log_admin_action(request, 'activity_manage', f'创建活动分类: {name}')
        return JsonResponse({
            'success': True,
            'message': '分类创建成功',
            'category': {
                'id': category.id,
                'name': category.name,
                'description': category.description,
                'icon': category.icon,
                'is_default': category.is_default,
                'created_at': category.created_at.strftime('%Y-%m-%d %H:%M')
            }
        })

    return JsonResponse({'success': False, 'message': '请求方法错误'})


@login_required
@user_passes_test(is_admin_user)
def category_edit(request, category_id):
    """编辑活动分类"""
    category = get_object_or_404(ActivityCategory, id=category_id)

    if request.method == 'POST':
        name = request.POST.get('name')
        description = request.POST.get('description', '')
        icon = request.POST.get('icon', '')
        is_default = request.POST.get('is_default') == 'on'

        if not name:
            return JsonResponse({'success': False, 'message': '分类名称不能为空'})

        # 检查分类名称是否已被其他分类使用
        if ActivityCategory.objects.filter(name=name).exclude(id=category_id).exists():
            return JsonResponse({'success': False, 'message': '分类名称已存在'})

        # 更新分类
        category.name = name
        category.description = description
        category.icon = icon
        category.is_default = is_default
        category.save()

        log_admin_action(request, 'activity_manage', f'编辑活动分类: {name}')
        return JsonResponse({
            'success': True,
            'message': '分类更新成功',
            'category': {
                'id': category.id,
                'name': category.name,
                'description': category.description,
                'icon': category.icon,
                'is_default': category.is_default
            }
        })

    # GET请求返回分类数据
    return JsonResponse({
        'success': True,
        'category': {
            'id': category.id,
            'name': category.name,
            'description': category.description,
            'icon': category.icon,
            'is_default': category.is_default
        }
    })


@login_required
@user_passes_test(is_admin_user)
def category_delete(request, category_id):
    """删除活动分类"""
    if request.method == 'POST':
        category = get_object_or_404(ActivityCategory, id=category_id)
        category_name = category.name

        # 检查是否有活动使用此分类
        activity_count = Activity.objects.filter(category=category).count()
        if activity_count > 0:
            return JsonResponse({
                'success': False,
                'message': f'无法删除该分类，有 {activity_count} 个活动正在使用此分类'
            })

        # 删除分类
        category.delete()

        log_admin_action(request, 'activity_manage', f'删除活动分类: {category_name}')
        return JsonResponse({'success': True, 'message': '分类删除成功'})

    return JsonResponse({'success': False, 'message': '请求方法错误'})


# 积分管理相关视图
@login_required
@user_passes_test(is_admin_user)
def points_management(request):
    """积分管理"""
    # 用户积分列表
    user_points_list = UserPoints.objects.select_related('user').order_by('-total_points')

    # 搜索功能
    search_query = request.GET.get('search', '')
    if search_query:
        user_points_list = user_points_list.filter(
            Q(user__username__icontains=search_query) |
            Q(user__nickname__icontains=search_query) |
            Q(user__email__icontains=search_query)
        )

    # 积分范围筛选
    points_min = request.GET.get('points_min', '')
    points_max = request.GET.get('points_max', '')
    if points_min:
        user_points_list = user_points_list.filter(available_points__gte=points_min)
    if points_max:
        user_points_list = user_points_list.filter(available_points__lte=points_max)

    # 统计信息
    total_points_users = UserPoints.objects.count()
    total_points = UserPoints.objects.aggregate(total=Sum('total_points'))['total'] or 0
    total_available_points = UserPoints.objects.aggregate(total=Sum('available_points'))['total'] or 0
    avg_points = UserPoints.objects.aggregate(avg=Avg('total_points'))['avg'] or 0

    context = {
        'user_points_list': user_points_list,
        'search_query': search_query,
        'points_min': points_min,
        'points_max': points_max,
        'total_points_users': total_points_users,
        'total_points': total_points,
        'total_available_points': total_available_points,
        'avg_points': round(avg_points, 1),
    }
    return render(request, 'dashboard/points_management.html', context)


@login_required
@user_passes_test(is_admin_user)
def points_records_management(request):
    """积分记录管理"""
    points_records = PointsRecord.objects.select_related('user').order_by('-created_at')

    # 搜索功能
    search_query = request.GET.get('search', '')
    if search_query:
        points_records = points_records.filter(
            Q(user__username__icontains=search_query) |
            Q(description__icontains=search_query)
        )

    # 类型筛选
    type_filter = request.GET.get('type', '')
    if type_filter:
        points_records = points_records.filter(type=type_filter)

    # 时间筛选
    date_from = request.GET.get('date_from', '')
    date_to = request.GET.get('date_to', '')
    if date_from:
        points_records = points_records.filter(created_at__date__gte=date_from)
    if date_to:
        points_records = points_records.filter(created_at__date__lte=date_to)

    # 统计信息
    total_records = points_records.count()
    total_points_added = PointsRecord.objects.filter(points__gt=0).aggregate(total=Sum('points'))['total'] or 0
    total_points_used = PointsRecord.objects.filter(points__lt=0).aggregate(total=Sum('points'))['total'] or 0

    # 积分类型统计
    points_type_stats = PointsRecord.objects.values('type').annotate(
        count=Count('id'),
        total_points=Sum('points')
    ).order_by('-count')

    context = {
        'points_records': points_records,
        'search_query': search_query,
        'type_filter': type_filter,
        'date_from': date_from,
        'date_to': date_to,
        'total_records': total_records,
        'total_points_added': total_points_added,
        'total_points_used': abs(total_points_used),
        'points_type_stats': points_type_stats,
    }
    return render(request, 'dashboard/points_records_management.html', context)


@login_required
@user_passes_test(is_admin_user)
def rewards_management(request):
    """奖品管理"""
    rewards = Reward.objects.all().order_by('-created_at')

    # 搜索功能
    search_query = request.GET.get('search', '')
    if search_query:
        rewards = rewards.filter(
            Q(name__icontains=search_query) |
            Q(description__icontains=search_query)
        )

    # 类型筛选
    type_filter = request.GET.get('type', '')
    if type_filter:
        rewards = rewards.filter(type=type_filter)

    # 状态筛选
    status_filter = request.GET.get('status', '')
    if status_filter == 'active':
        rewards = rewards.filter(is_active=True)
    elif status_filter == 'inactive':
        rewards = rewards.filter(is_active=False)
    elif status_filter == 'out_of_stock':
        rewards = rewards.filter(stock=0)

    # 统计信息
    total_rewards = rewards.count()
    active_rewards = Reward.objects.filter(is_active=True).count()
    out_of_stock_rewards = Reward.objects.filter(stock=0).count()
    total_exchanges = RewardExchange.objects.count()

    context = {
        'rewards': rewards,
        'search_query': search_query,
        'type_filter': type_filter,
        'status_filter': status_filter,
        'total_rewards': total_rewards,
        'active_rewards': active_rewards,
        'out_of_stock_rewards': out_of_stock_rewards,
        'total_exchanges': total_exchanges,
    }
    return render(request, 'dashboard/rewards_management.html', context)


@login_required
@user_passes_test(is_admin_user)
def reward_create(request):
    """创建奖品"""
    if request.method == 'POST':
        name = request.POST.get('name')
        description = request.POST.get('description', '')
        reward_type = request.POST.get('type')
        points_required = request.POST.get('points_required')
        stock = request.POST.get('stock')
        is_active = request.POST.get('is_active') == 'on'

        if not all([name, reward_type, points_required, stock]):
            return JsonResponse({'success': False, 'message': '请填写所有必填字段'})

        try:
            points_required = int(points_required)
            stock = int(stock)

            if points_required <= 0:
                return JsonResponse({'success': False, 'message': '所需积分必须大于0'})
            if stock < 0:
                return JsonResponse({'success': False, 'message': '库存不能为负数'})

        except ValueError:
            return JsonResponse({'success': False, 'message': '积分和库存必须为数字'})

        # 创建奖品
        reward = Reward.objects.create(
            name=name,
            description=description,
            type=reward_type,
            points_required=points_required,
            stock=stock,
            is_active=is_active
        )

        log_admin_action(request, 'system_manage', f'创建奖品: {name}')
        return JsonResponse({
            'success': True,
            'message': '奖品创建成功',
            'reward_id': reward.id
        })

    return JsonResponse({'success': False, 'message': '请求方法错误'})


@login_required
@user_passes_test(is_admin_user)
def reward_edit(request, reward_id):
    """编辑奖品"""
    reward = get_object_or_404(Reward, id=reward_id)

    if request.method == 'POST':
        name = request.POST.get('name')
        description = request.POST.get('description', '')
        reward_type = request.POST.get('type')
        points_required = request.POST.get('points_required')
        stock = request.POST.get('stock')
        is_active = request.POST.get('is_active') == 'on'

        if not all([name, reward_type, points_required, stock]):
            return JsonResponse({'success': False, 'message': '请填写所有必填字段'})

        try:
            points_required = int(points_required)
            stock = int(stock)

            if points_required <= 0:
                return JsonResponse({'success': False, 'message': '所需积分必须大于0'})
            if stock < 0:
                return JsonResponse({'success': False, 'message': '库存不能为负数'})

        except ValueError:
            return JsonResponse({'success': False, 'message': '积分和库存必须为数字'})

        # 更新奖品
        reward.name = name
        reward.description = description
        reward.type = reward_type
        reward.points_required = points_required
        reward.stock = stock
        reward.is_active = is_active
        reward.save()

        log_admin_action(request, 'system_manage', f'编辑奖品: {name}')
        return JsonResponse({
            'success': True,
            'message': '奖品更新成功'
        })

    # GET请求返回奖品数据
    return JsonResponse({
        'success': True,
        'reward': {
            'id': reward.id,
            'name': reward.name,
            'description': reward.description,
            'type': reward.type,
            'points_required': reward.points_required,
            'stock': reward.stock,
            'is_active': reward.is_active
        }
    })


@login_required
@user_passes_test(is_admin_user)
def reward_delete(request, reward_id):
    """删除奖品"""
    if request.method == 'POST':
        reward = get_object_or_404(Reward, id=reward_id)
        reward_name = reward.name

        # 检查是否有兑换记录
        exchange_count = RewardExchange.objects.filter(reward=reward).count()
        if exchange_count > 0:
            return JsonResponse({
                'success': False,
                'message': f'无法删除该奖品，有 {exchange_count} 条兑换记录与此奖品关联'
            })

        # 删除奖品
        reward.delete()

        log_admin_action(request, 'system_manage', f'删除奖品: {reward_name}')
        return JsonResponse({'success': True, 'message': '奖品删除成功'})

    return JsonResponse({'success': False, 'message': '请求方法错误'})


@login_required
@user_passes_test(is_admin_user)
def reward_exchange_management(request):
    """兑换记录管理"""
    exchanges = RewardExchange.objects.select_related('user', 'reward').order_by('-created_at')

    # 搜索功能
    search_query = request.GET.get('search', '')
    if search_query:
        exchanges = exchanges.filter(
            Q(user__username__icontains=search_query) |
            Q(reward__name__icontains=search_query)
        )

    # 状态筛选
    status_filter = request.GET.get('status', '')
    if status_filter:
        exchanges = exchanges.filter(status=status_filter)

    # 时间筛选
    date_from = request.GET.get('date_from', '')
    date_to = request.GET.get('date_to', '')
    if date_from:
        exchanges = exchanges.filter(created_at__date__gte=date_from)
    if date_to:
        exchanges = exchanges.filter(created_at__date__lte=date_to)

    # 统计信息
    total_exchanges = exchanges.count()
    pending_exchanges = RewardExchange.objects.filter(status='pending').count()
    completed_exchanges = RewardExchange.objects.filter(status='completed').count()
    total_points_used = RewardExchange.objects.aggregate(total=Sum('points_used'))['total'] or 0

    context = {
        'exchanges': exchanges,
        'search_query': search_query,
        'status_filter': status_filter,
        'date_from': date_from,
        'date_to': date_to,
        'total_exchanges': total_exchanges,
        'pending_exchanges': pending_exchanges,
        'completed_exchanges': completed_exchanges,
        'total_points_used': total_points_used,
    }
    return render(request, 'dashboard/reward_exchange_management.html', context)


@login_required
@user_passes_test(is_admin_user)
def update_exchange_status(request, exchange_id):
    """更新兑换状态"""
    if request.method == 'POST':
        exchange = get_object_or_404(RewardExchange, id=exchange_id)
        status = request.POST.get('status')

        if status not in ['pending', 'completed', 'cancelled']:
            return JsonResponse({'success': False, 'message': '无效的状态'})

        old_status = exchange.status
        exchange.status = status

        # 如果标记为完成，记录完成时间
        if status == 'completed' and old_status != 'completed':
            exchange.completed_at = timezone.now()

        exchange.save()

        # 记录操作日志
        log_admin_action(request, 'system_manage',
                         f'更新兑换状态: {exchange.user.username} - {exchange.reward.name} ({old_status} -> {status})')

        return JsonResponse({
            'success': True,
            'message': '状态更新成功',
            'status': status,
            'completed_at': exchange.completed_at.strftime('%Y-%m-%d %H:%M') if exchange.completed_at else None
        })

    return JsonResponse({'success': False, 'message': '请求方法错误'})


@login_required
@user_passes_test(is_admin_user)
def manual_points_adjust(request, user_id):
    """手动调整用户积分"""
    if request.method == 'POST':
        user = get_object_or_404(User, id=user_id)
        adjustment_type = request.POST.get('adjustment_type')  # 'add' or 'deduct'
        points = request.POST.get('points')
        description = request.POST.get('description', '')

        if not all([adjustment_type, points, description]):
            return JsonResponse({'success': False, 'message': '请填写所有必填字段'})

        try:
            points = int(points)
            if points <= 0:
                return JsonResponse({'success': False, 'message': '积分必须大于0'})
        except ValueError:
            return JsonResponse({'success': False, 'message': '积分必须为数字'})

        # 获取用户积分记录
        user_points, created = UserPoints.objects.get_or_create(user=user)

        # 调整积分
        if adjustment_type == 'add':
            user_points.total_points += points
            user_points.available_points += points
            record_points = points
            action_description = f"管理员增加积分: {description}"
        else:  # deduct
            if user_points.available_points < points:
                return JsonResponse({'success': False, 'message': '用户积分不足，无法扣除'})
            user_points.available_points -= points
            user_points.used_points += points
            record_points = -points
            action_description = f"管理员扣除积分: {description}"

        user_points.save()

        # 创建积分记录
        PointsRecord.objects.create(
            user=user,
            points=record_points,
            type='admin_adjust',
            description=action_description
        )

        log_admin_action(request, 'user_manage',
                         f'调整用户积分: {user.username} ({adjustment_type} {points} points) - {description}')

        return JsonResponse({
            'success': True,
            'message': '积分调整成功',
            'new_available_points': user_points.available_points,
            'new_total_points': user_points.total_points
        })

    return JsonResponse({'success': False, 'message': '请求方法错误'})